package com.tyk.bookstore.front.order.mq;

import com.rabbitmq.client.Channel;
import com.tyk.bookstore.front.common.mq.RabbitManager;
import com.tyk.bookstore.front.order.model.emume.CancelReason;
import com.tyk.bookstore.front.order.model.query.OrderCancelQuery;
import com.tyk.bookstore.front.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author tyk
 * @description MqReceiver
 */
@Service
@RequiredArgsConstructor
public class MqReceiver {

    /**
     * 消息唯一标识的key
     */
    @Value("${mine.mq.rabbit.id-key}")
    private String idKey;


    /**
     * 默认重试次数
     */
    @Value("${mine.mq.rabbit.retry}")
    public int retryCount;

    /**
     * 重试次数的key
     */
    @Value("${mine.mq.rabbit.args.retry-count}")
    private String retryCountKey;

    private final OrderService orderService;
    private final RabbitManager rabbitManager;

    /**
     * 延时取消订单
     *
     * @param orderId 订单ID
     * @param msg     消息
     * @param channel 通道
     */
    @SneakyThrows
    @RabbitListener(queues = MqConstant.ORDER_CANCEL_QUEUE)
    public void receiveDelayMsg(Long orderId, Message msg, Channel channel) {
        MessageProperties ps = msg.getMessageProperties();
        try {
            // 获取传递的参数
            Long memberId = Long.valueOf(
                    ps.getHeader(MqConstant.ARGS_MEMBER_ID)
            );
            // 取消订单
            orderService.cancel(new OrderCancelQuery(orderId, CancelReason.OVERTIME_UNPAID), memberId);
        } catch (Exception e) {

            // 写日志，通知维护人员
            System.out.println(e);
            System.out.println("订单取消失败, orderId=" + orderId);

            // 查看是否可以重试
            int count = this.retryCount;
            String rcs = ps.getHeader(this.retryCountKey);
            if (rcs != null) count = Integer.parseInt(rcs);

            // 转非延迟消息进行重试
            if (count > 0)
                rabbitManager.sendMsg(
                        ps.getReceivedExchange(),
                        ps.getReceivedRoutingKey(),
                        orderId,
                        ps.getHeader(this.idKey),
                        Map.of(
                                MqConstant.ARGS_MEMBER_ID, ps.getHeader(MqConstant.ARGS_MEMBER_ID),
                                this.retryCountKey,String.valueOf(--count)
                        )
                );

        }

        // 确认消息已被消费
        // 无论是否成功处理，此消息确已被消费者成功接收
        channel.basicAck(ps.getDeliveryTag(), false);

    }

}
